/**
 * TeachizenMailLibarary
 * MailSender.java
 *
 * Copyright 2013 bnsworks
 * Written by htkim
 *	2013. 10. 10. first written.
 *
 * note:
 */
package com.teachizen.mail.send.smtp;

import java.security.*;
import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

import com.sun.mail.smtp.*;
import com.sun.mail.util.*;
import com.teachizen.mail.receive.*;
import com.teachizen.mail.send.smpt.*;

/**
 * @author htkim
 *
 */
public class MailSender {

	private MailSender() { }

	private final static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
	private final static MailSender instance = new MailSender();

	private static Properties props;
	private static Session session;

	public static MailSender getInstance() {
		return instance;
	}
	
	public void init(final ServerInfo info) throws GeneralSecurityException {
	
		props = System.getProperties();
		props.put("mail.smtp.host", info.url);
		props.put("mail.smtp.port", info.port);
		if (info.secure != null || !info.secure.equals("")) {
			props.put("mail.smtp.auth", "true");
			if (info.secure.equalsIgnoreCase("ssl")) {
				props.put("mail.smtp.ssl.enable", "true");
			} else {
				props.put("mail.smtp.starttls.enable", "true");
			}
			props.put("mail.smtp.ssl.trust", info.url);
		}
		
		session = Session.getDefaultInstance(props, 
				new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(info.username, info.password);
			}
		});
		session.setDebug(true);
	}
	
	public void cleanup() {
		
	}
	
	public void send(final SmtpMessage message) throws MessagingException {
		Message mimeMessage = new MimeMessage(session);
		mimeMessage.setFrom(new InternetAddress(message.from));
		mimeMessage.setRecipient(Message.RecipientType.TO,
				new InternetAddress(message.recipient));
		mimeMessage.setSubject(message.subject);
		mimeMessage.setText(message.text);
		Transport.send(mimeMessage);
	}
}
